package com.jlwl.houseservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jlwl.houseservice.entity.ServiceRequest;
import com.jlwl.houseservice.mapper.ServiceRequestMapper;
import com.jlwl.houseservice.service.ServiceRequestService;
import com.jlwl.houseservice.vo.ServiceRequestCreateVO;
import com.jlwl.houseservice.vo.ServiceRequestQueryVO;
import com.jlwl.houseservice.vo.ServiceRequestReplyVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 * 服务需求Service实现类
 */
@Service
public class ServiceRequestServiceImpl extends ServiceImpl<ServiceRequestMapper, ServiceRequest> implements ServiceRequestService {

    @Override
    @Transactional
    public boolean createServiceRequest(ServiceRequestCreateVO createVO, Integer userId) {
        ServiceRequest serviceRequest = new ServiceRequest();
        serviceRequest.setUserId(userId);
        serviceRequest.setServiceType(createVO.getServiceType());
        serviceRequest.setDescription(createVO.getDescription());
        serviceRequest.setExpectedTime(createVO.getExpectedTime());
        serviceRequest.setBudget(createVO.getBudget());
        serviceRequest.setAddressDetail(createVO.getAddressDetail());
        serviceRequest.setContactName(createVO.getContactName());
        serviceRequest.setContactPhone(createVO.getContactPhone());
        serviceRequest.setStatus("待处理");
        serviceRequest.setCreatedAt(LocalDateTime.now());
        serviceRequest.setUpdatedAt(LocalDateTime.now());
        
        return save(serviceRequest);
    }

    @Override
    public Page<ServiceRequest> pageUserList(ServiceRequestQueryVO queryVO, Integer userId) {
        LambdaQueryWrapper<ServiceRequest> queryWrapper = new LambdaQueryWrapper<>();
        
        // 只查询当前用户的服务需求
        queryWrapper.eq(ServiceRequest::getUserId, userId);
        
        // 构建查询条件
        buildQueryWrapper(queryWrapper, queryVO);
        
        // 默认按创建时间倒序排序
        queryWrapper.orderByDesc(ServiceRequest::getCreatedAt);
        
        // 分页查询
        return page(new Page<>(queryVO.getPage(), queryVO.getSize()), queryWrapper);
    }

    @Override
    public ServiceRequest getUserServiceRequestDetail(Integer id, Integer userId) {
        return getOne(new LambdaQueryWrapper<ServiceRequest>()
                .eq(ServiceRequest::getId, id)
                .eq(ServiceRequest::getUserId, userId));
    }

    @Override
    public Page<ServiceRequest> pageAdminList(ServiceRequestQueryVO queryVO) {
        LambdaQueryWrapper<ServiceRequest> queryWrapper = new LambdaQueryWrapper<>();
        
        // 构建查询条件
        buildQueryWrapper(queryWrapper, queryVO);
        
        // 默认按创建时间倒序排序
        queryWrapper.orderByDesc(ServiceRequest::getCreatedAt);
        
        // 分页查询
        return page(new Page<>(queryVO.getPage(), queryVO.getSize()), queryWrapper);
    }

    @Override
    public ServiceRequest getAdminServiceRequestDetail(Integer id) {
        return getById(id);
    }

    @Override
    @Transactional
    public boolean replyServiceRequest(Integer id, ServiceRequestReplyVO replyVO) {
        ServiceRequest serviceRequest = getById(id);
        if (serviceRequest == null) {
            return false;
        }
        
        // 构建回复内容
        StringBuilder replyBuilder = new StringBuilder();
        replyBuilder.append("回复内容：").append(replyVO.getReplyContent()).append("\n");
        replyBuilder.append("建议价格：").append(replyVO.getPrice()).append("元\n");
        
        if (StringUtils.hasText(replyVO.getSuggestTime())) {
            replyBuilder.append("建议服务时间：").append(replyVO.getSuggestTime());
        }
        
        // 更新服务需求
        serviceRequest.setReply(replyBuilder.toString());
        serviceRequest.setReplyTime(LocalDateTime.now());
        serviceRequest.setStatus("已回复");
        serviceRequest.setUpdatedAt(LocalDateTime.now());
        
        return updateById(serviceRequest);
    }

    @Override
    @Transactional
    public boolean updateServiceRequestStatus(Integer id, String status) {
        ServiceRequest serviceRequest = getById(id);
        if (serviceRequest == null) {
            return false;
        }
        
        // 更新状态
        serviceRequest.setStatus(status);
        serviceRequest.setUpdatedAt(LocalDateTime.now());
        
        return updateById(serviceRequest);
    }
    
    /**
     * 构建查询条件
     */
    private void buildQueryWrapper(LambdaQueryWrapper<ServiceRequest> queryWrapper, ServiceRequestQueryVO queryVO) {
        // 关键词搜索
        if (StringUtils.hasText(queryVO.getKeyword())) {
            queryWrapper.and(wrapper -> wrapper
                    .like(ServiceRequest::getServiceType, queryVO.getKeyword())
                    .or()
                    .like(ServiceRequest::getDescription, queryVO.getKeyword())
                    .or()
                    .like(ServiceRequest::getContactName, queryVO.getKeyword())
                    .or()
                    .like(ServiceRequest::getContactPhone, queryVO.getKeyword())
            );
        }
        
        // 状态筛选
        if (StringUtils.hasText(queryVO.getStatus())) {
            queryWrapper.eq(ServiceRequest::getStatus, queryVO.getStatus());
        }
        
        // 日期范围筛选
        if (queryVO.getStartDate() != null) {
            queryWrapper.ge(ServiceRequest::getCreatedAt, queryVO.getStartDate().atStartOfDay());
        }
        
        if (queryVO.getEndDate() != null) {
            queryWrapper.le(ServiceRequest::getCreatedAt, queryVO.getEndDate().plusDays(1).atStartOfDay());
        }
    }
} 